import {Component, Input, OnChanges, OnInit, ViewChild, SimpleChanges} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {EquipMainDataHttpServices} from '../http/http';
import {HttpErrorResponse} from '@angular/common/http';
import {Util, ParentCategory} from './util';


interface DeviceDefTableItem {
  code: string;
  name: string;
  deviceDefCatName: string;
  deviceDefCatId: string;
  deviceDefCatAllPaId: string,
  deviceDefCatAllPaName: string,
  createUserName: string;
  createTime: string;
  id: number;
}

interface ModalTableItem {
  code: string;
  name: string;
  attrDefName: string;
  remark: string;
}

@Component({
  selector: 'device-def-form',
  styleUrls: ['./components.less'],
  template: `
    <form nz-form [formGroup]="deviceDefForm" class="attr-type-form">
      <nz-form-item>
        <nz-form-label nzRequired [nzSpan]="8">
          编码
        </nz-form-label>
        <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
          <input nz-input formControlName="code"/>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label nzRequired [nzSpan]="8">
          名称
        </nz-form-label>
        <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
          <input nz-input formControlName="name"/>
        </nz-form-control>
      </nz-form-item>
      <nz-form-item>
        <nz-form-label nzRequired [nzSpan]="8">
          分类
        </nz-form-label>
        <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
          <nz-cascader [nzOptions]="cascaderOption" formControlName="deviceDefCatId" nzChangeOnSelect
                       (nzSelectionChange)="onChanges($event)"></nz-cascader>
        </nz-form-control>
      </nz-form-item>
    </form>
    <ng-container *ngIf="mode !== 'create'">
      <button nz-button (click)="modalVisible= true ">新增</button>
      <nz-table #modalTable [nzShowSizeChanger]="true" [nzShowQuickJumper]="true"
                [nzData]="tableData" [nzLoading]="loading" [nzFrontPagination]="false"
                [nzTotal]="pagination.total" [(nzPageSize)]="pagination.size" [(nzPageIndex)]="pagination.start"
                (nzPageIndexChange)="pagination.start = $event;loadModalTable()"
                (nzPageSizeChange)="pagination.size = $event;loadModalTable()" class="device-attr-modal-table">
        <thead>
        <tr>
          <th>属性名</th>
          <th>属性定义</th>
          <th>备注</th>
          <th nzAlign="center">操作</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let item of modalTable.data">
          <td>{{ item.name }}</td>
          <td>{{ item.attrDefName }}</td>
          <td>{{ item.remark }}</td>
          <td class='modal-option-td' nzAlign="center">
            <span (click)="onModalUpdate(item)">修改</span>
            <span (click)="onModalDelete(item.id)">删除</span>
          </td>
        </tr>
        </tbody>
      </nz-table>
    </ng-container>
    <nz-modal [(nzVisible)]="modalVisible" (nzOnOk)="onModalSubmit()" (nzOnCancel)="modalVisible=false;modalForm.reset()"
              [nzTitle]="modalMode==='create'? '新增属性定义':'修改属性定义'">
      <form nz-form [formGroup]="modalForm" class="attr-type-form">
        <nz-form-item>
          <nz-form-label nzRequired [nzSpan]="8">
            属性定义
          </nz-form-label>
          <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
            <input nz-input formControlName="attrDefName"/>
          </nz-form-control>
        </nz-form-item>
        <nz-form-item>
          <nz-form-label nzRequired [nzSpan]="8">
            备注
          </nz-form-label>
          <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
            <input nz-input formControlName="remark"/>
          </nz-form-control>
        </nz-form-item>
        <nz-form-item>
          <nz-form-label nzRequired [nzSpan]="8">
            属性选择
          </nz-form-label>
          <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
            <nz-select *ngIf="allDef" formControlName="attrDefId" [nzOptions]="allDef" (ngModelChange)="onModelChange($event)">
            </nz-select>
          </nz-form-control>
        </nz-form-item>
      </form>
    </nz-modal>


  `
})
export class DeviceDefFormComponent implements OnChanges, OnInit {

  @Input() mode: string;
  @Input() editData: any;
  @Input() deviceDefForm!: FormGroup;

  constructor(private fb: FormBuilder, private http: EquipMainDataHttpServices, private util: Util) {
  }

  cascaderOption: any;
  selectCategoryData = {
    id: null,
    name: null,
    deviceDefCatAllPaId: null,
    deviceDefCatAllPaName: null
  };
  pagination = {
    size: 10,
    start: 1,
    total: 0
  };
  tableData: Array<ModalTableItem>;
  loading = false;
  modalVisible = false;
  allDef: any;
  currentSelectedDef: any;
  modalForm!: FormGroup;
  modalMode = 'create';
  modalEditData: any;

  onCreate(successCallback): void {
    if (this.deviceDefForm.valid) {
      const {code, name} = this.deviceDefForm.value;
      const allParentId = this.selectCategoryData && this.selectCategoryData.deviceDefCatAllPaId;
      const allParentName = this.selectCategoryData && this.selectCategoryData.deviceDefCatAllPaName;
      this.http.createDeviceDef({
        code,
        name,
        deviceDefCatId: this.selectCategoryData && this.selectCategoryData.id,
        deviceDefCatName: this.selectCategoryData && this.selectCategoryData.name,
        allParentId,
        allParentName
      }).subscribe((res) => {
        if (res.code === 0) {
          successCallback();
          this.selectCategoryData = {
            id: null,
            name: null,
            deviceDefCatAllPaId: null,
            deviceDefCatAllPaName: null
          };
        }
      }, (err: HttpErrorResponse) => {
      });
    }
  }

  onUpdate(successCallback): void {
    const {code, name} = this.deviceDefForm.value;
    const allParentId = this.selectCategoryData && this.selectCategoryData.deviceDefCatAllPaId;
    const allParentName = this.selectCategoryData && this.selectCategoryData.deviceDefCatAllPaName;
    this.http.updateDeviceDef({
      code,
      name,
      deviceDefCatId: this.selectCategoryData && this.selectCategoryData.id,
      deviceDefCatName: this.selectCategoryData && this.selectCategoryData.name,
      allParentId,
      allParentName,
      id: this.editData.id
    })
      .subscribe((res) => {
        if (res.code === 0) {
          successCallback();
          this.selectCategoryData = {
            id: null,
            name: null,
            deviceDefCatAllPaId: null,
            deviceDefCatAllPaName: null
          };
        }
      }, (err: HttpErrorResponse) => {
      });
  }

  onModalSubmit(): void {
    const {remark, attrDefName, attrDefId} = this.modalForm.value;
    const deviceDefId = this.editData.id;
    const {code, name, id} = this.currentSelectedDef;
    if (this.modalMode === 'create') {
      this.http.createDeviceAttrRelation({
        name, attrDefId, deviceDefId, remark, attrDefName
      }).subscribe((res) => {
        if (res.code === 0) {
          this.loadModalTable();
        }
      }, (error: HttpErrorResponse) => {
      });
    } else {
      this.http.updateDeviceAttrRelation({
        name, attrDefId,
        deviceDefId, remark, attrDefName, id: this.modalEditData.id
      }).subscribe((response) => {
        if (response.code === 0) {
          this.loadModalTable();
          this.modalMode = 'create';
        }
      }, () => {
      });
    }
    this.modalVisible = false;
    this.modalForm.reset();
  }

  onModalUpdate(data): void {
    this.modalMode = 'edit';
    this.modalVisible = true;
    this.modalEditData = data;
    this.modalForm.patchValue(data);
    console.log(this.modalForm);
  }


  onModalDelete(id): void {
    this.http.deleteDeviceAttrRelation({id}).subscribe(
      (res) => {
        if (res.code === 0) {
          this.loadModalTable();
        }
      }, (error: HttpErrorResponse) => {

      }
    );
  }

  onModelChange(data): void {
    this.allDef && this.allDef.length && this.allDef.map(item => {
      if (item.value == data) {
        this.currentSelectedDef = item.origin;
      }
    });
    console.log(this.currentSelectedDef, this.allDef);
  }

  onChanges(array: Array<ParentCategory>): void {
    const idArray = [], nameArray = [];
    for (let item of array) {
      idArray.push(item.id);
      nameArray.push(item.name);
    }
    this.selectCategoryData = {
      id: array[array.length - 1].id,
      name: array[array.length - 1].name,
      deviceDefCatAllPaId: idArray.join(','),
      deviceDefCatAllPaName: nameArray.join(',')
    };
    console.log(this.selectCategoryData);
  }


  loadModalTable(): void {
    const {start, size} = this.pagination;
    this.http.queryDeviceAttrRelation({start: start - 1, size, id: this.editData.id}).subscribe((res) => {
        this.tableData = res.data.content;
        this.pagination.total = res.data.totalElements;
        this.loading = false;
      },
      (error: HttpErrorResponse) => {
        this.loading = false;
        this.tableData = [];
      });
  }

  ngOnChanges(changes: SimpleChanges): void {
    const {size, start} = this.pagination;
    if (this.mode !== 'create' && this.editData && this.deviceDefForm) {
      const params = {...this.editData, allParentId: this.editData.deviceDefCatAllPaId, allParentName: this.editData.deviceDefCatAllPaName};
      let cascadeData = this.util.getCascaderDataY(params);
      cascadeData = cascadeData.concat({value: this.editData.deviceDefCatId.toString(), label: this.editData.deviceDefCatName});
      this.deviceDefForm.patchValue({...this.editData, deviceDefCatId: cascadeData});
      this.loadModalTable();
    }
  }

  ngOnInit(): void {
    this.http.getAllDeviceParentsCategories().subscribe((res) => {
      if (res.code === 0) {
        this.cascaderOption = this.util.getCascaderData(res.data);
      }
    }, (err: HttpErrorResponse) => {
    });
    this.http.getAllDef().subscribe((res) => {
      if (res.code === 0) {
        const newArray = [];
        res.data.map(item => {
          let {name, id} = item;
          newArray.push({value: Number.parseInt(id), label: name, origin: item});
        });
        console.log(newArray);
        this.allDef = newArray;
      }
    }, (err: HttpErrorResponse) => {
    });
    this.modalForm = this.fb.group({
      attrDefName: [null, Validators.required],
      remark: [null, Validators.required],
      attrDefId: [null, Validators.required],
    });
  }
}


@Component({
  selector: 'app-equip-device-def-mgmt',
  styleUrls: ['./components.less'],
  template: `
    <div class="equipMainDataMgmtContainer">
      <div class="equip-main-data-mgmt-bar">
        <div><span>单位码：</span><input nz-input placeholder="输入类型编码查询" [(ngModel)]="keyword"/></div>
        <button nz-button nzType="primary" (click)="loadTable()">查询</button>
        <button nz-button style="background:'green';color:'#ffffff';border-color:'transparent'" (click)="visibleObject.toForm = true">新增
        </button>
      </div>
      <nz-table #attrDefTable [nzShowSizeChanger]="true" [nzShowQuickJumper]="true"
                [nzData]="tableData" [nzLoading]="loading" [nzFrontPagination]="false"
                [nzTotal]="pagination.total" [(nzPageSize)]="pagination.size" [(nzPageIndex)]="pagination.start"
                (nzPageIndexChange)="onPageIndexChange($event)" (nzPageSizeChange)="onPageSizeChange($event)">
        <thead>
        <tr>
          <th>编码</th>
          <th>名称</th>
          <th>分类</th>
          <th>创建人</th>
          <th>创建时间</th>
          <th nzAlign="center">操作</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let defItem of attrDefTable.data">
          <td>{{ defItem.code }}</td>
          <td>{{ defItem.name }}</td>
          <td>{{ defItem.deviceDefCatName }}</td>
          <td>{{ defItem.createUserName }}</td>
          <td>{{ defItem.createTime }}</td>
          <td class='option-td' nzAlign="center">
            <span (click)="onEdit(defItem)">修改</span>
            <span (click)="visibleObject.toDelete = true; deleteId = defItem.id">删除</span>
          </td>
        </tr>
        </tbody>
      </nz-table>
    </div>

    <nz-modal [(nzVisible)]="visibleObject.toForm" [nzTitle]="modalTitle" (nzOnCancel)="onCancel()"
              (nzOnOk)="onSubmit()" [nzWidth]="744">
      <ng-template #modalTitle>新增设备定义</ng-template>
      <ng-container *nzModalContent>
        <device-def-form #myForm [mode]="mode" [editData]="editData" [deviceDefForm]="deviceDefMgmtForm"></device-def-form>
      </ng-container>
    </nz-modal>

    <nz-modal [(nzVisible)]="visibleObject.toDelete" nzTitle="警告" (nzOnCancel)="visibleObject.toDelete=false" (nzOnOk)="onDelete()">
      <ng-container *nzModalContent>
        您确认要删除此项吗？
      </ng-container>
    </nz-modal>
  `
})
export class DeviceDefMgmtComponent implements OnInit {
  constructor(private http: EquipMainDataHttpServices, private fb: FormBuilder) {
  }

  @ViewChild('myForm') formComponent;
  deviceDefMgmtForm!: FormGroup;
  mode = 'create';
  tableData!: Array<DeviceDefTableItem>;
  editData!: DeviceDefTableItem;
  visibleObject: any = {
    toForm: false,
    toDelete: false
  };
  loading = true;
  keyword = '';
  deleteId: any;
  pagination: any = {
    size: 10,
    start: 1,
    total: undefined,
  };


  loadTable(): void {
    const {start, size} = this.pagination;
    this.http.queryDeviceDef({start: start - 1, size, keyword: this.keyword}).subscribe(
      (res) => {
        if (res.code === 0) {
          this.tableData = res.data.content;
          this.pagination.total = res.data.totalElements;
          this.loading = false;
        }
      }, (err: HttpErrorResponse) => {
        this.loading = false;
        this.tableData = [];
      });
  }

  onSubmit(): void {
    if (this.mode === 'create') {
      this.formComponent.onCreate(() => {
        this.loadTable();
        this.deviceDefMgmtForm.reset();
      });
    } else {
      this.formComponent.onUpdate(() => {
        this.loadTable();
        this.mode = 'create';
        this.deviceDefMgmtForm.reset();
      });
    }

    this.visibleObject.toForm = false;
  }


  onCancel(): void {
    this.visibleObject.toForm = false;
    this.mode = 'create';
    this.deviceDefMgmtForm.reset();
  }

  onEdit(data): void {
    this.visibleObject.toForm = true;
    this.mode = 'edit';
    this.editData = data;
  }

  onDelete(): void {
    this.visibleObject.toDelete = false;
    this.http.deleteDef(this.deleteId).subscribe(
      (res) => {
        if (res.code === 0) {
          this.loadTable();
        }
      }, (err: HttpErrorResponse) => {
      });
  }

  onPageIndexChange(data): void {
    this.pagination.start = data;
    this.loadTable();
  }

  onPageSizeChange(data): void {
    this.pagination.size = data;
    this.loadTable();
  }

  ngOnInit(): void {
    this.loadTable();
    this.deviceDefMgmtForm = this.fb.group({
      code: [null, Validators.required],
      name: [null, Validators.required],
      deviceDefCatId: [null, Validators.required]
      ,
    });
  }

}

